//
//  FinalFindEventView.m
//  eticket
//
//  Created by AnhQuocNguyen on 4/15/13.
//  Copyright (c) 2013 SoinMedia. All rights reserved.
//

#import "FinalFindEventView.h"

@implementation FinalFindEventView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}



- (void)dealloc {
    SAFE_RELEASE_VIEW(_lbTitle);
    SAFE_RELEASE_OBJECT(_category);
    SAFE_RELEASE_VIEW(_tblView);
    SAFE_RELEASE_OBJECT(_urlString);
    SAFE_RELEASE_OBJECT(mHud);
    [super dealloc];
}

#pragma mark - MBProgressHUD
-(void)initHUD:(NSString *)alert {
    if (mHud) {
        [mHud removeFromSuperview];
        SAFE_RELEASE_OBJECT(mHud);
    }
    mHud = [[MBProgressHUD alloc] initWithView:self];
    //    mHud.delegate = self;
    mHud.labelText = alert;
    mHud.dimBackground = YES;
    [self addSubview:mHud];
    
}
-(void)waitting{
    while (mLoading) {
        usleep(5000);
    }
}

#pragma mark - Setup tableView
- (void)setupUI{
    
    ////////////////////////////////////////////////////////////////////////////
    //Setup tableView
    if (!_tblView) {
        _tblView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, self.bounds.size.width, [Utilities isDeviceFourInches] ? self.bounds.size.height -  130 : self.bounds.size.height -  135)];
        _tblView.backgroundColor = [UIColor clearColor];
        _tblView.separatorStyle = UITableViewCellSelectionStyleNone;
        _tblView.delegate = self;
        _tblView.dataSource = self;
        [self addSubview:_tblView];
    }
    else{
        [_tblView reloadData];
    }
}

#pragma mark - reloadData
- (void)reloadData{
    mLoading = YES;
    [self initHUD:@"Loading...."];
    [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
    
    
    self.backgroundColor = [UIColor clearColor];
    self.clipsToBounds = YES;
    self.layer.borderWidth = 1.;
    self.layer.cornerRadius = 2;
    self.layer.borderColor = [[UIColor colorWithRed:237/255 green:237/255 blue:237/255 alpha:.3] CGColor];
    [self getDataFromServer];
    
}


#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self reloadData];
    }
}

#pragma mark - cancelRequest
- (void)cancelRequest{
    [requestServer clearDelegatesAndCancel];
}


#pragma mark - get data froms server
- (void)getDataFromServer{
    dispatch_async(kBgQueue, ^{
        NSURL *url = [NSURL URLWithString:_urlString];
        requestServer = [ASIFormDataRequest requestWithURL:url];
        [requestServer setTimeOutSeconds:20];
        [requestServer setCompletionBlock:^{
            NSError *error = nil;
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[requestServer responseData] options:kNilOptions error:&error];
            
            /////////////////////////////////////////////////////////////////////
            //Set error server
            if (error) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error description] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            
            /////////////////////////////////////////////////////////////////////
            //Set error json
            NSDictionary *jsonError = [jsonDic objectForKey:@"error"];
            if ([[jsonError objectForKey:@"code"] intValue] != 200) {
                NSArray *messageArray = [jsonError objectForKey:@"message"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[messageArray objectAtIndex:0] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            
            /////////////////////////////////////////////////////////////////////
            //Set Data
            NSDictionary *dicData = [jsonDic objectForKey:@"data"];
            
            SAFE_RELEASE_OBJECT(_arrayListData);
            _arrayListData = [[NSMutableArray alloc] init];
            NSArray *list = [dicData objectForKey: @"events"] ;
            
            //////////////////////////
            //Set title for text label
            _lbTitle.text = [NSString stringWithFormat:@"%d results found",[list count]];
            for (NSInteger i = 0 ; i < [list count]; i++) {
                NSDictionary *dicCate = [list objectAtIndex:i];
                EventTicket *event = [[EventTicket alloc] init];
                event.titleEvent = [dicCate objectForKey:@"title"];
                event.idEvent = [dicCate objectForKey:@"id"];
                event.slug = [dicCate objectForKey:@"slug"];
                event.thumbnailEvent = [dicCate objectForKey:@"thumbnail"];
                event.startTimeEvent = [dicCate objectForKey:@"start_time"];
                event.address = [dicCate objectForKey:@"address"];
                
                NSDictionary *jsonCategory = [dicCate objectForKey:@"categories"];
                NSDictionary *jsonPrimary = [jsonCategory objectForKey:@"second"];
                event.categoryEvent = [jsonPrimary objectForKey:@"title"];
                
                [_arrayListData addObject:event];
                SAFE_RELEASE_OBJECT(event);
            }

            //////////////////////////
            //Set tableView
            [self setupUI];
            _tblView.delegate = self;
            _tblView.dataSource = self;
            mLoading = NO;
        }];
        [requestServer setFailedBlock:^{
            mLoading = NO;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Loading faild !!!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
            alert.tag = ALERT_LISTEVENT_HOME;
            [alert show];
            SAFE_RELEASE_OBJECT(alert);
        }];
        [requestServer startSynchronous];
    });
}


- (IBAction)btnBack_FirstView:(id)sender{
    _lbTitle.text = @"";
    [_arrayListData removeAllObjects];
    [_tblView reloadData];
    if ([_finalFindEventDelegate respondsToSelector:@selector(finalFindEventWithBack:)]) {
        [_finalFindEventDelegate finalFindEventWithBack:self];
    }
}

#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_arrayListData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"FinalViewCell";
    FinalViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FinalViewCell" owner:self options:nil];
        for (id curr in nib) {
            if ([curr isKindOfClass:[FinalViewCell class]]) {
                cell = (FinalViewCell *)curr;
                cell.exclusiveTouch = YES;
                break;
            }
        }
    }
    EventTicket *event = [_arrayListData objectAtIndex:indexPath.row];
    cell.lbTitle.text = event.titleEvent;
    cell.lbAddress.text = event.address;
    cell.lbCategory.text = _category;
    
    NSArray *arrayStartTime = [event.startTimeEvent componentsSeparatedByString:@" "];
    cell.lbStartTime.text = [arrayStartTime objectAtIndex:0];

    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!_eventDetailView) {
        POOL_START
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EventDetailView" owner:self options:nil];
        _eventDetailView = (EventDetailView *)[nib objectAtIndex:0];
        _eventDetailView.frame = CGRectMake(330, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
        [self.superview addSubview:_eventDetailView];
        POOL_END
    }
    
    EventTicket *eventTicket = (EventTicket *)[_arrayListData objectAtIndex:indexPath.row];
    _eventDetailView.eventSlug = eventTicket.slug;
    [_eventDetailView setupEventDetailView];
    [_eventDetailView getDataFromServer];
    _eventDetailView.eventDetailViewDelegate = self;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frameTempCategory = self.frame;
        frameTempCategory.origin.x = - 320;
        self.frame = frameTempCategory;
        
        CGRect frametemp = _eventDetailView.frame;
        frametemp.origin.x = 0;
        _eventDetailView.frame = frametemp;
        
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}


/////////////////////////////////////////////////////////////////////////////////
//Tu eventDetail quay ve
#pragma mark - EventDetailView Delegate
- (void)eventDetailViewWithback:(EventDetailView *)evenDetailView{
    
    self.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frameTempCategory = self.frame;
        frameTempCategory.origin.x = 0;
        self.frame = frameTempCategory;
        
        CGRect frametemp = evenDetailView.frame;
        frametemp.origin.x = 330;
        evenDetailView.frame = frametemp;
        
    } completion:^(BOOL finished) {
        _eventDetailView.eventDetailViewDelegate = nil;
    }];
}

@end
